package com.unit.manager;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.inject.Named;
import javax.sql.DataSource;

import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.RowProcessor;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import com.unit.dbutils.processor.GeneraBeanProcessor;

@Named("dbUtilsManager")
public class DbUtilsManager {

	private DataSource dataSource;
	private QueryRunner queryRunner;

	public <T> T toBean(String sql, Class<T> beanClass, Map<String, String> specialColumnMap) throws SQLException {
		GeneraBeanProcessor bean = new GeneraBeanProcessor(specialColumnMap);
		RowProcessor rowProcessor = new BasicRowProcessor(bean);
		BeanHandler<T> handler = new BeanHandler<T>(beanClass, rowProcessor);
		return queryRunner.query(sql, handler);
	}
	
	public <T> List<T> toBeanList(String sql, Class<T> beanClass, Map<String, String> specialColumnMap) throws SQLException {
		GeneraBeanProcessor bean = new GeneraBeanProcessor(specialColumnMap);
		RowProcessor rowProcessor = new BasicRowProcessor(bean);
		BeanListHandler<T> handler = new BeanListHandler<T>(beanClass, rowProcessor);
		return queryRunner.query(sql, handler);
	}
	
	/**
	 * 每行纪录保存到主键为key的map对象中，里面map的key为列名，value为值
	 * @param sql
	 * @param pkColumn 主键字段，类型为Long
	 * @return
	 * @throws SQLException
	 */
	public Map<Long,Map<String, Object>> toKeyDataMap(String sql, String pkColumn) throws SQLException{
		return queryRunner.query(sql,  new KeyedHandler<Long>(pkColumn)); 
	}
	
	public Map<String, Object> toFieldDataMapByJdbcId(String sql) throws SQLException{
		return queryRunner.query(sql, new MapHandler());
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public QueryRunner getQueryRunner() {
		if(queryRunner == null) {
			queryRunner = new QueryRunner(dataSource, true);
		}
		return queryRunner;
	}


}
